package cn.yunhe.controller;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.yunhe.model.User;
import cn.yunhe.util.PageUtil;
import service.UserService;


@WebServlet("/MainServlet")
public class MainServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String pageIndex = req.getParameter("pageIndex");
		
		if (pageIndex == null) {
			pageIndex = "1";
		}
		
		int currPage = Integer.parseInt(pageIndex);

		UserService userSerivce = new UserService();

		// 总条数
		int count = userSerivce.getCount();
		PageUtil pu = new PageUtil();
		// 总页数
		int totalPage = pu.getTotalPage(count, PageUtil.pageSize);
       //对首页和尾页的处理
		
		if(currPage< 1) {
    	   currPage=1;
			
		}else if(currPage>totalPage){
			currPage=totalPage;
		}
		
		List<User> list = userSerivce.getUserByPage(currPage, PageUtil.pageSize);

		req.setAttribute("list", list);
		req.setAttribute("pageIndex",pageIndex);
		
		req.setAttribute("totalPage", totalPage);
        req.getRequestDispatcher("main.jsp").forward(req, resp);
        
        
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doGet(req, resp);
	}

}
